let userInfo = {}
const db = wx.cloud.database()
Component({
	properties: {
    blogId: String,
    blog: Object
	},

	options: {
		styleIsolation: 'apply-shared'
	},

	data: {
		showLogin: false, // 登录组件是否显示
		showModal: false // 底部弹出层
	},

	methods: {
		// 弹出评论
		onComment() {
			wx.getSetting({
				success: res => {
					if (res.authSetting['scope.userInfo']) {
						wx.getUserInfo({
							success: res => {
								// 显示评论弹窗
								this.setData({
									showModal: true
								})
                userInfo = res.userInfo
							}
						})
					} else {
						// 显示授权弹出层
						this.setData({
							showLogin: true
						})
					}
				}
			})
		},
		// 授权成功
		onLoginSuccess(e) {
      userInfo = e.detail
			// 授权框消失，显示评论框
			this.setData({
				showLogin: false
			}, () => {
				this.setData({
					showModal: true
				})
			})
		},
		// 未授权
		onLoginFail() {
			wx.showModal({
				title: '授权用户才能尽心评论',
				content: ''
			})
		},
    // 发送评论
    onSend(e) {
      const formId = e.detail.formId // 获取 formId 
      const content = e.detail.value.content // 获取 textare 的内容
      // 评论
      if (content.trim() === '') {
        wx.showModal({
          title: '评论内容不能为空',
          content: '',
        })
        return
      }
      wx.showLoading({
        title: '评论中...',
        mask: true
      })

      // 博客Id、头像、昵称、创建时间、内容、
      db.collection('blog-comment').add({
        data: {
          content,
          blogId: this.properties.blogId,
          createTime: db.serverDate(),
          nickName: userInfo.nickName,
          avatarUrl: userInfo.avatarUrl
        }
      }).then(res => {
        // 推送模板消息
        wx.cloud.callFunction({
          name: 'sendMessage',
          data: {
            content,
            formId,
            blogId: this.properties.blogId
          }
        }).then(res => {
          console.log(res)
        })

        wx.hideLoading()
        wx.showToast({
          title: '评论成功',
        })
        this.setData({
          showModal: false
        })

        // 父元素刷新评论页面
        this.triggerEvent('refreshCommentList')
      })
    }
	}
})
